package com.dgut.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dgut.app.service.WishService;
import com.dgut.common.dto.WishDTO;
import com.dgut.common.entity.Wish;
import com.dgut.common.entity.WxUser;
import com.dgut.common.mapper.WishMapper;
import com.dgut.common.utils.ApiException;
import com.dgut.common.utils.ErrorEnum;
import com.dgut.common.utils.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author IT00ZYQ
 * @Date 2021/4/5 13:21
 **/
@Service
public class WishServiceImpl implements WishService {


    private final WishMapper wishMapper;

    public WishServiceImpl(WishMapper wishMapper) {
        this.wishMapper = wishMapper;
    }

    @Override
    public void addWish(WishDTO dto, String token) {
        WxUser user = JwtUtil.getUser(token);
        wishMapper.insert(Wish.builder()
                .content(dto.getContent())
                .title(dto.getTitle())
                .userId(user.getId())
                .build());
    }

    @Override
    public List<Wish> listWish(String token) {
        WxUser user = JwtUtil.getUser(token);
        QueryWrapper<Wish> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", user.getId());
        wrapper.orderByDesc("create_time");
        return wishMapper.selectList(wrapper);
    }

    @Override
    public Wish detail(Integer id) {
        return wishMapper.selectById(id);
    }

    @Override
    public void delete(Integer id) {
        wishMapper.deleteById(id);
    }

    @Override
    public void update(WishDTO dto) {
        if (dto.getId() == null) {
            throw new ApiException(ErrorEnum.PARAM_ERROR);
        }
        Wish wish = wishMapper.selectById(dto.getId());
        if (wish == null) {
            throw new ApiException("心愿信息不存在");
        }
        BeanUtils.copyProperties(dto, wish);
        wishMapper.updateById(wish);
    }
}
